//
//  T3FTNPolygon.swift
//  t3_map
//
//  Created by Cunhai Li on 2024/10/22.
//

import QMapKit
import UIKit

class T3FTNPolygon: NSObject {

    typealias Value = (fillColor: UIColor?, strokeColor: UIColor?)

    private(set) var options: T3FPolygonOptions

    /// 重置颜色
    var resetColor: ((Value) -> Void)?

    /// SDK内置的Polygon
    let realPolygon: QPolygon

    var updatePoints: (([CLLocationCoordinate2D]) -> Bool)?

    init(options: T3FPolygonOptions, realPolygon: QPolygon) {
        self.options = options
        self.realPolygon = realPolygon
    }
}

extension T3FTNPolygon: T3FPolygon {

    func update(points: [CLLocationCoordinate2D]) {
        if let updatePoints = updatePoints {
            let result = updatePoints(points)
            /// 更新成功，需要同步修改options的点集
            guard result else {
                return
            }
            options.points = points
        }
    }

    /// 设置 fillColor
    /// - Parameter fillColor: UIColor
    func setup(fillColor: UIColor) {
        options.fillColor = fillColor
        resetColor?((fillColor, nil))
    }

    /// 设置 strokeColor
    /// - Parameter strokeColor: UIColor
    func setup(strokeColor: UIColor) {
        options.strokeColor = strokeColor
        resetColor?((nil, strokeColor))
    }

    func container(coordinate: CLLocationCoordinate2D) -> Bool {

        guard coordinate.latitude > 0, coordinate.longitude > 0 else {
            return false
        }
        return QPolygonContainsPoint(QMapPointForCoordinate(coordinate), realPolygon.points, realPolygon.pointCount)
    }
}

